import React, { useEffect, useState, useRef } from 'react';
import { Button, Input, message } from 'antd';
import useRefState from '@/pages/hooks/usehooks/useRefState';

// 参考地址: https://juejin.cn/post/6844904005919834119
export default function SSE() {
  const [messageList, setMessageList] = useRefState([]);
  const [value, setValue] = useState('');
  const [, setRefresh] = useState(new Date());
  const webSocket = useRef();
  useEffect(() => {
    webSocket.current = new WebSocket('ws://localhost:8080/websocket');
    webSocket.current.onopen = function() {
      console.log('连接成功～');
    };

    webSocket.current.onerror = function() {
      message.error('连接发生错误～');
    };

    webSocket.current.onmessage = function(event) {
      console.log('接受的数据:', event.data);
      setMessageList(prev => [JSON.parse(event.data), ...prev]);
      setRefresh(new Date());
    };

    return () => {
      webSocket.current.close();
    };
  }, []);

  const handleSend = () => {
    webSocket.current.send(`前端向后端发送的数据: ${value}`);
  };
  return (
    <ul style={{ padding: 0 }}>
      <Input value={value} onChange={e => setValue(e.target.value)} />
      <br />
      <Button onClick={handleSend} type="primary">
        发送消息
      </Button>
      {messageList.current.map(msg => (
        <ol key={msg.key} style={{ margin: 20, background: '#fff', padding: 10 }}>
          <span>
            <strong style={{ fontSize: 18 }}>标题：</strong>
            <span>{msg.title}</span>
          </span>
          <br />
          <span>
            <strong style={{ fontSize: 18 }}>内容：</strong>
            <span>{msg.content}</span>
          </span>
          <div style={{ color: '#ccc', textAlign: 'right', paddingRight: 10 }}>
            创建时间: {msg.createTime}
          </div>
        </ol>
      ))}
    </ul>
  );
}
